import {Component, ViewEncapsulation, ViewChild, Input} from '@angular/core';
import {Utility} from '../../services/app.utility';
import {IdeaService} from '../../services/app.idea';
import {UserService} from '../../services/app.user';
import {Ideas} from '../shared/ideas/idea.component';
import {BaThemeSpinner}  from '../../theme/services';
import {Constants} from '../../../app/common/app.constants';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'recent',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./recent.scss'],
    templateUrl: './recent.html'
})
export class Recent {
    @Input()
    constants:Constants;
    @ViewChild('ideas')
    public idea:Ideas;
    public versioning:boolean;
    public totalIdeasDeatail = {
        skipItem: 0,
        itemsperPage: 20,
        sortParameter: 'createdAt',
        sortOrder: 'descending',
        toDate: '17/10/2017',
        fromDate: '01/04/2014'

    };
    public start:any;
    public end:any;
    public check:any;
    public totalIdeas:any;

    constructor(private utility:Utility, private spinner:BaThemeSpinner, public ideaService:IdeaService, private userService:UserService) {
        this.constants = new Constants();
        this.versioning = false;
        // API call for get user info
        this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => this.userInfoFail(error)
        );

        this.start = 0;
        this.check = 0;

        // function for start timeline count
        this.startCount();

    };

    // function for call API to get recent idea
    public getRecentIdeas() {
        this.spinner.showProgress();
        this.ideaService.ideaList(this.totalIdeasDeatail).subscribe(
            data => this.success(data),
            error => this.fail(error)
        );
    }

    // Function call after get responce from user info API
    public userInfoSuccess(data) {
        console.log("recent");
        if (data.version === 'Version_1') {
            this.versioning = false;
        } else if (data.version === 'Version_2') {
            this.versioning = false;
        } else if (data.version === 'Version_4') {
            this.versioning = false;
        } else if (data.version === 'Version_6') {
            this.versioning = false;
        } else {
            this.versioning = true;
        }
    }

    // Function for call recent idea after load view
    ngAfterViewInit() {
        this.getRecentIdeas();
    }

    // Function for after fail user info API
    public  userInfoFail(err) {
    }

    // Function call after success recent idea API
    public success(result) {
        if (this.versioning) {
            for (let x = 0; x < result.ideaList.length; x++) {
                if (result.ideaList[x].citationArray !== undefined) {
                    for (let y = 0; y < result.ideaList[x].citationArray.length; y++) {
                        result.ideaList[x].content = result.ideaList[x].content.replace(result.ideaList[x].citationArray[y], '<span class="keywordColor">' + result.ideaList[x].citationArray[y] + '</span>');
                    }
                }
            }
        }
        this.spinner.hideProgress(3500);
        this.totalIdeas = result;
        this.idea.setIdeasInMasonry(result);
    }

    // Function for after fail recent idea info API
    public fail(error) {
        this.spinner.hideProgress();
    }

    // Function for show more idea when click on show more button
    public showMoreIdea() {
        this.totalIdeasDeatail.skipItem += this.totalIdeasDeatail.itemsperPage;
        this.getRecentIdeas();
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
      let seq = {
        sequence: {
          "pageName": 'recentIdea',
          "timeSpent": this.start
        }

      };
      this.userService.setUrlSeq(seq).subscribe();
    }

    // Function call after view for log API
    ngAfterViewChecked() {
        let self = this;
        $('.RecentIdea').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        let self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        let domTarget = event.target;
        let domTargetString = domTarget.toString();
        let stringDemo = domTargetString.substr(12, 25);
        let index = stringDemo.indexOf('E');
        let dom = stringDemo.substr(0, index);
        let text = $(event.target).unbind().text();


        let input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        if (event.target.className.indexOf('ion-thumbsup') >= 0) {
            let input = {
                'target': 'Like',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-thumbsdown') >= 0) {
            let input = {
                'target': 'Dislike',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-android-star') >= 0) {
            let input = {
                'target': 'Points',
                'value': '',
                'action': buttons
            };
            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-heart') >= 0) {
            let input = {
                'target': 'Favourite',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-chatboxes') >= 0) {
            let input = {
                'target': 'Comment',
                'value': '',
                'action': buttons
            };
            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-alert-circled') >= 0) {
            let input = {
                'target': 'Abuse',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (text.indexOf('×') >= 0) {
            let input = {
                'target': 'Closed modal',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-edit') >= 0) {
            let data = {
                'target': this.constants.URL + 'admin/edituser',
                'value': 'admin/edituser',
                'action': 'redirect'
            };

            self.userService.setUserLogs(data).subscribe();
        } else {
            self.setUserLogs(input);
        }
    }

    // Function for call API for log
    public setUserLogs(input) {
        this.userService.setUserLogs(input).subscribe();
    }

}
